import logging
import time
from datetime import datetime

from flask import request, jsonify

from iHome import db, redis_store
from iHome.api_1_0 import api
from iHome.models import House, Order
from iHome.utils.xuehua import Snow

"""
订单的下单
/orders/   POST
参数：  用户id  房屋id  开始时间   结束时间
成功  返回 订单id
失败  4001 4010  0
"""


@api.route('/orders/', methods=['POST'])
def order_data():
    user_id = 2
    params = request.json

    house_id = params.get('house_id')
    start_date = params.get('start_date')
    end_date = params.get('end_date')

    """判断是否为空"""
    if not all([house_id, start_date, end_date]):
        return jsonify(errno='4001', errmsg='参数不能为空')

    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')
    days = (end_date - start_date).days

    """判断房屋是否存在"""
    try:
        house = House.query.get(house_id)
    except Exception as e:
        return jsonify(errno='4001', errmsg='房屋不存在')

    """计算价格"""
    total_amount = house.price * days

    """订单是否下重复了"""
    count = Order.query.filter(
        Order.house_id == house_id,
        Order.begin_date < end_date,
        Order.end_date > start_date
    ).count()

    if count > 0:
        return jsonify(errno=4004, errmsg='订单日期冲突了， 请重新选择！')

    """雪花算法 四部分 最高位0时间戳机器id 序列号"""
    or_id = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + str(time.time()).replace('.', '')[-7:])
    print(or_id)

    order = Order(
        id=or_id,
        user_id=user_id,
        house_id=house_id,
        begin_date=start_date,
        end_date=end_date,
        days=days,

        amount=total_amount,
        house_price=house.price
    )

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(errno=4002, errmsg='下单失败！')

    redis_store.delete('custom' + str(user_id))
    redis_store.delete('landlord' + str(user_id))

    return jsonify(errno=0, errmsg="下单成功！", data={"order_id": order.id})

"""
获取订单接口
房东房客进入界面有区别
url /user/orders/
参数  用户id  角色
根据角色进行操作
返回数据 data ：{
        ‘orders’: order_list
    }
"""
@api.route('/user/orders/')
def get_orders():

    user_id = 1
    role = request.args.get('role')

    if not role:
        return jsonify(errno='4001', errmsg='参数有误')

    relo_key = role + str(user_id)
    relo_data = redis_store.get(relo_key)

    if role == "custom":

        if relo_data:
            return jsonify(errno='0', errmsg="请求成功", data={"orders": eval(relo_data)})

        """查询当前自己下了哪些订单"""
        orders = Order.query.filter_by(user_id=user_id).order_by(Order.create_time.desc())

    else:

        if relo_data:
            return jsonify(errno='0', errmsg="请求成功", data={"orders": eval(relo_data)})

        """查询自己房屋都有哪些订单"""
        houses = House.query.filter_by(user_id=user_id).all()
        house_id_list = [house.id for house in houses]
        orders = Order.query.filter(Order.house_id.in_(house_id_list)).order_by(Order.create_time.desc())

    orders_dict = []

    for order in orders:
        orders_dict.append(order.to_dict())

    if not relo_data:
        redis_store.setex(relo_key, 3600, str(orders_dict))

    return jsonify(errno='0', errmsg="请求成功", data={"orders": orders_dict})

"""
接单拒单  /orders/<order_id>/status/
PUT
用户id  订单id   状态status  action（接单还是拒单） 拒单原因
响应  0 

"""
@api.route('/orders/<order_id>/status/', methods=['PUT'])
def set_order_status(order_id):
    """接收参数  order_id  status"""
    user_id = 1

    # 获取参数&判断参数
    params = request.get_json()
    action = params.get('action')
    if action not in ("accept", "reject"):
        return jsonify(errno='4001', errmsg='参数错误')

    # 通过订单id查询出订单模型
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_ACCEPT").first()
        house = order.house
    except Exception as e:
        db.session.rollback()
        return jsonify(errno='4001', errmsg='查询数据错误')

    # 判断订单是否存在并且当前房屋的用户id是当前用户的id
    if order and house.user_id != user_id:
        return jsonify(errno='4001', errmsg='数据有误')

    if action == "accept":
        # 接单
        order.status = "WAIT_COMMENT"
    elif action == "reject":
        # 获取拒单原因
        reason = params.get("reason")
        if not reason:
            return jsonify(errno='4001', errmsg="未填写拒单原因")

        # 设置状态为拒单并且设置拒单原因
        order.status = "REJECTED"
        order.comment = reason

    # 保存到数据库
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno='4001', errmsg="保存订单状态失败")

    redis_store.delete('custom' + str(user_id))
    redis_store.delete('landlord' + str(user_id))

    return jsonify(errno='0', errmsg="OK")



@api.route('/orders/<order_id>/comment/', methods=["PUT"])
def set_order_comment(order_id):

    """获取参数"""
    user_id = 2
    params = request.get_json()
    comment = params.get('comment')
    if not comment:
        return jsonify(errno='4001', errmsg='请输入评论内容')

    # 通过订单id查询出订单模型
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == "WAIT_COMMENT").first()
        house = order.house
    except Exception as e:
        logging.error(e)
        return jsonify(errno='4001', errmsg='查询数据错误')

    # 更新数据

    order.status = "COMPLETE"
    order.comment = comment
    # 更新数据库
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno='4001', errmsg='更新数据库失败')

    # 删除redis中缓存的房屋详情信息,因为房屋详情信息已经更新
    try:
        redis_store.delete('custom' + str(user_id))
        redis_store.delete('landlord' + str(user_id))
    except Exception as e:
        logging.error(e)

    return jsonify(errno='0', errmsg='OK')


























